// pages/life/face_authorization/face_authorization.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    files: [],
    deviceP: "back",
    hidePlus: true,
    hidePhotoPlus: true,
    isReason: false,
    isDialogAuthCamera: false,
    household_register_type: -1,
    comeBackProvince: false,
    isDialogAuthCamera: false,
    comeBackCounty: true,
    comeBackArea: true,
    addressPopup: false,
    comeBackBuilding: true,
    comeBackCell: true,
    comeBackYard: false,
    loading: false,
    tabIndex: 0,
    tabCommunityIndex: 0,
    communityLabel: "请选择小区",
    addressLabel: "请选择居住地址",
    communityTab: [{
      text: '选择省'
    }, {
      text: ''
    }, {
      text: ''
    }, {
      text: ''
    }],
    addressTab: [{
      text: '选择院落'
    }, {
      text: ''
    }, {
      text: ''
    }, {
      text: ''
    }],
    arrayNative: [{
      value: 1,
      key: "自住"
    }, {
      value: 0,
      key: "租住"
    }],
    native_value: "",
    people_type_value: "",
    is_native: "",
    people_type: "",
    obj: {
      loading: false,
      mobile_num: "",
      head_img_url: [],
      identity_img_url: []
    },
    community_area_code: "",
    roomId: "",
    roomName: "",
    fromTo: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: app.globalData.appTitle,
    })
    this.setData({
      theme: app.globalData.theme
    });
    app.setNavigationBarColor();
    if (options.fromto) {
      this.setData({
        fromTo: options.fromto
      });
    }
    wx.getSystemInfo({
      success: res => {
        this.setData({
          height: res.windowHeight
        });
      }
    });
    this.getCommunity();
    this.getOptionList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 小区选择
   */
  facePopupCommunity: function() {
    this.setData({
      loading: false,
      communityPopup: true
    });
  },
  /**
   * 获取省数据
   */
  getProvince: function() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let provinceArray = [];
    app.wxGetRequest("/wechart/mine/getProvince", {}).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          provinceArray.push({
            key: item.area_name,
            value: item.area_id + "," + item.area_name
          });
        });
        this.setData({
          provinceArray: provinceArray,
          tabCommunityIndex: 0,
        });
      }
    });
  },
  /**
   * 点击省
   */
  clickProvince: function(e) {
    let value = e.detail.value;
    if (!this.data.comeBackProvince && value) {
      this.setData({
        loading: true
      });
      this.getCity(value);
    } else {
      this.setData({
        comeBackProvince: false
      });
    }
  },
  /**
   * 获取市数据
   */
  getCity: function(province) {
    let value = province.split(",");
    let countArray = [];
    app.wxGetRequest("/wechart/mine/getAreaByAreaId", {
      area_id: value[0]
    }).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          countArray.push({
            key: item.area_name,
            value: item.area_id + "," + item.area_name
          });
        });
        this.setData({
          countArray: countArray,
          communityTab: [{
            text: value[1]
          }, {
            text: '选择市'
          }, {
            text: ''
          }, {
            text: ''
          }],
          tabCommunityIndex: 1,
          province: value
        });
        setTimeout(() => {
          this.setData({
            loading: false
          });
        }, 500);
      }
    });
  },

  /**
   * 点击市
   */
  clickCounty: function(e) {
    let value = e.detail.value;
    if (!this.data.comeBackCounty && value) {
      this.setData({
        loading: true
      });
      this.getArea(value);
    } else {
      this.setData({
        comeBackCounty: false
      });
    }
  },

  /**
   * 获取区数据
   */
  getArea: function(county) {
    let value = county.split(",");
    let areaArray = [];
    app.wxGetRequest("/wechart/mine/getAreaByAreaId", {
      area_id: value[0]
    }).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          areaArray.push({
            key: item.area_name,
            value: item.area_code + "," + item.area_name
          });
        });
        this.setData({
          areaArray: areaArray,
          communityTab: [{
            text: this.data.province[1]
          }, {
            text: value[1]
          }, {
            text: '选择区'
          }, {
            text: ''
          }],
          tabCommunityIndex: 2,
          county: value
        });
        setTimeout(() => {
          this.setData({
            loading: false
          });
        }, 500);
      }
    });
  },
  /**
   * 点击区
   */
  clickArea: function(e) {
    let value = e.detail.value;
    if (!this.data.comeBackArea && value) {
      this.setData({
        loading: true
      });
      this.getCommunity(value);
    } else {
      this.setData({
        comeBackArea: false
      });
    }
  },
  /**
   * 获取小区数据
   */
  getCommunity: function() {
    let yardsArray = [];
    app.wxGetRequest("/wechart/mine/getYardByAreaCode", {
      area_code: app.globalData.parentAreaCode
    }).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          yardsArray.push({
            key: item.yard_name,
            value: item.yard_id + "," + item.yard_name + "," + item.area_code
          });
        });
        this.setData({
          yardsArray: yardsArray,
          tabIndex: 0
        });
      }
    });
  },

  /**
   * 点击院落
   */
  clickYards: function(e) {
    let value = e.detail.value;
    if (!this.data.comeBackYard && value) {
      this.setData({
        loading: true
      });
      this.getBuilding(value);
    } else {
      this.setData({
        comeBackYard: false
      });
    }
  },
  /**
   * 获取楼栋数据
   */
  getBuilding: function(yard) {
    let value = yard.split(",");
    let buildingsArray = [];
    app.wxGetRequest("/wechart/mine/getBuildByYardId", {
      yard_id: value[0]
    }).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          buildingsArray.push({
            key: item.building_name,
            value: item.building_id + "," + item.building_name
          });
        });
        this.setData({
          buildingsArray: buildingsArray,
          addressTab: [{
            text: value[1]
          }, {
            text: '选择楼栋'
          }, {
            text: ''
          }, {
            text: ''
          }],
          tabIndex: 1,
          yard: value
        });
        setTimeout(() => {
          this.setData({
            loading: false
          });
        }, 500);
      }
    });
  },
  /**
   * 点击楼栋
   */
  clickBUilding: function(e) {
    let value = e.detail.value;
    if (!this.data.comeBackBuilding && value) {
      this.setData({
        loading: true
      });
      this.getCell(value);
    } else {
      this.setData({
        comeBackBuilding: false
      });
    }
  },
  /**
   * 获取单元数据
   */
  getCell: function(building) {
    let value = building.split(",");
    let cellsArray = [];
    app.wxGetRequest("/wechart/mine/getCellByBuildId", {
      build_id: value[0]
    }).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          cellsArray.push({
            key: item.cell_name,
            value: item.cell_id + "," + item.cell_name
          });
        });
        this.setData({
          cellsArray: cellsArray,
          addressTab: [{
            text: this.data.yard[1],
          }, {
            text: value[1]
          }, {
            text: '选择单元'
          }, {
            text: ''
          }],
          tabIndex: 2,
          building: value
        });
        setTimeout(() => {
          this.setData({
            loading: false
          });
        }, 500);
      }
    });
  },

  /**
   * 点击单元
   */
  clickCells: function(e) {
    let value = e.detail.value;
    if (!this.data.comeBackCell && value) {
      this.setData({
        loading: true
      });
      this.getRoom(value);
    } else {
      this.setData({
        comeBackCell: false
      });
    }
  },
  /**
   * 获取房间数据
   */
  getRoom: function(cell) {
    let value = cell.split(",");
    let roomsArray = [];
    app.wxGetRequest("/wechart/mine/getRoomByCellId", {
      cell_id: value[0]
    }).then(result => {
      if (result.data.code == 1) {
        result.data.data.forEach((item, index) => {
          roomsArray.push({
            key: item.room_name,
            value: item.room_id + "," + item.room_name
          });
        });

        this.setData({
          roomsArray: roomsArray,
          addressTab: [{
            text: this.data.yard[1],
          }, {
            text: this.data.building[1]
          }, {
            text: value[1]
          }, {
            text: '选择房间'
          }],
          tabIndex: 3,
          cell: value,
        });
        setTimeout(() => {
          this.setData({
            loading: false
          });
        }, 500);
      }
    });
  },

  /**
   * 点击房间
   */
  clickRooms: function(e) {
    let value = e.detail.value.split(",");
    this.setData({
      addressLabel: this.data.yard[1] + this.data.building[1] + " " + this.data.cell[1] + " " + value[1],
      roomId: value[0],
      roomName: value[1],
      addressPopup: false
    });
  },
  /**
   * 点击小区选择tab切换
   */
  clickCommunityTabs: function(e) {
    let value = e.detail.value;
    if (value == 0) {
      this.setData({
        tabCommunityIndex: value,
        communityTab: [{
          text: this.data.province[1]
        }, {
          text: ''
        }, {
          text: ''
        }, {
          text: ''
        }],
        county: "",
        area: "",
        comeBackProvince: true
      });

    } else if (value == 1) {
      this.setData({
        tabCommunityIndex: value,
        communityTab: [{
          text: this.data.province[1]
        }, {
          text: this.data.county[1]
        }, {
          text: ''
        }, {
          text: ''
        }],
        area: "",
        comeBackCounty: true
      });
    } else if (value == 2) {
      this.setData({
        tabCommunityIndex: value,
        communityTab: [{
          text: this.data.province[1]
        }, {
          text: this.data.county[1]
        }, {
          text: this.data.area[1]
        }, {
          text: ''
        }],
        comeBackArea: true
      });
    } else if (value == 3) {
      this.setData({
        tabCommunityIndex: value,
        communityTab: [{
          text: this.data.province[1]
        }, {
          text: this.data.county[1]
        }, {
          text: this.data.area[1]
        }, {
          text: '选择院落'
        }],
      });
    }
  },
  /**
   * 点击居住地址tab切换
   */
  clickTabs: function(e) {
    let value = e.detail.value;
    if (value == 0) {
      this.setData({
        tabIndex: value,
        addressTab: [{
          text: this.data.yard[1]
        }, {
          text: ''
        }, {
          text: ''
        }, {
          text: ''
        }],
        building: "",
        cell: "",
        comeBackYard: true
      });

    } else if (value == 1) {
      this.setData({
        tabIndex: value,
        addressTab: [{
          text: this.data.yard[1]
        }, {
          text: this.data.building[1]
        }, {
          text: ''
        }, {
          text: ''
        }],
        cell: "",
        comeBackBuilding: true
      });
    } else if (value == 2) {
      this.setData({
        tabIndex: value,
        addressTab: [{
          text: this.data.yard[1]
        }, {
          text: this.data.building[1]
        }, {
          text: this.data.cell[1]
        }, {
          text: ""
        }],
        comeBackCell: true
      });
    } else if (value == 3) {
      this.setData({
        tabIndex: value,
        addressTab: [{
          text: this.data.yard[1]
        }, {
          text: this.data.building[1]
        }, {
          text: this.data.cell[1]
        }, {
          text: "选择房屋"
        }],
      });
    }
  },
  /**
   * 检查小区是否选择后才选择地址
   */
  facePopupAddress: function() {
    // if (!this.data.yardId) {
    //   this.setData({
    //     error: "请先选择小区"
    //   });
    // } else {
    //   this.setData({
    //     loading: false,
    //     addressPopup: true
    //   });
    // }
    this.setData({
      loading: false,
      addressPopup: true
    });
  },
  popupClose: function() {
    this.setData({
      communityPopup: false,
      addressPopup: false
    });
  },
  /**
   * 获取人员类型
   */
  getOptionList: function() {
    app.wxGetRequest("/mine/getOptionList", {}).then(result => {
      let arrayPeopleType = [];
      if (result.data.code == 1) {
        result.data.hz.forEach((item, index) => {
          arrayPeopleType.push({
            key: item.value,
            value: item.flag
          });
        });
        this.setData({
          arrayPeopleType: arrayPeopleType
        });
      } else {}
    });
  },
  /**
   * 获取下拉框人员类型值
   */
  bindSelectChangePeople: function(e) {
    let key = e.currentTarget.dataset.value;
    this.setData({
      people_type: e.detail.value,
    });
  },
  /**
   * 获取下拉框户籍类型值
   */
  bindSelectChangeNative: function(e) {
    let key = e.currentTarget.dataset.value;
    this.setData({
      is_native: e.detail.value
    });
  },
  /**
   * 重新点击按钮授权
   */
  openCameraSetting: function(e) {
    if (e.detail.authSetting["scope.camera"]) {
      this.setData({
        isDialogAuthCamera: false,
        camera: true
      });
    } else {
      this.setData({
        isDialogAuthCamera: true,
        camera: false
      });
    }
  },
  /**
   * 打开摄像头
   */
  opencamera: function(e) {
    let type = e.currentTarget.dataset.type;
    if (type == "identity_img_url") {
      this.setData({
        deviceP: "back",
        camera: true
      });
    } else {
      this.setData({
        deviceP: "front",
        camera: true
      });
    }
    console.error(this.data.deviceP)
    // if (!this.data.isDialogAuthCamera) {
    //   wx.authorize({
    //     scope: 'scope.camera',
    //     success: res => {
    //       this.setData({
    //         isDialogAuthCamera: false,
    //         camera: true
    //       });
    //     },
    //     fail: err => {
    //       this.setData({
    //         isDialogAuthCamera: true,
    //         camera: false
    //       });
    //     }
    //   });
    // }
  },
  // 拍照
  takePhoto: function(e) {
    let typeImg = e.currentTarget.dataset.type;
    if (typeImg == "identity_img_url") {
      wx.showLoading({
        title: '请稍等...',
        mask: true
      });
    } else {
      wx.showLoading({
        title: '请稍等...',
        mask: true
      });
    }
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        let progressUpdate=function(){};
        app.uploadFile(res.tempImagePath, progressUpdate).then((resultW)=>{
          if (resultW.code == 1) { //根据项目修改code
            let url;
            let options;
            if (typeImg == "identity_img_url") {
              url = "/mine/smartIdentificationCard";
              options = {
                identity_img_url: resultW.data[0]
              };
            } else {
              url = "/wechart/mine/getCertificationAvatar";
              options = {
                img_url: resultW.data[0]
              };
            }
            app.wxGetRequest(url, options).then(result => {
              if (typeImg == "identity_img_url") {
                if (result.data.result_list[0].code == 0) {
                  this.setData({
                    peopleInfo: result.data.result_list[0].data,
                    camera: false,
                    hidePlus: false,
                    ["obj." + "" + typeImg + ""]: [],
                    ["obj." + "" + typeImg + ""]: [resultW.data[0]]
                  });
                } else {
                  this.setData({
                    ["obj." + "" + typeImg + ""]: [],
                    peopleInfo: {},
                  });
                  app.alert("提示", "请点击拍摄清晰身份证头像页!");
                }
              } else {
                if (result.data.isOk) {
                  this.setData({
                    ["obj." + "" + typeImg + ""]: [],
                    ["obj." + "" + typeImg + ""]: [resultW.data[0]],
                    camera: false,
                    hidePhotoPlus: false,
                  });
                } else {
                  this.setData({
                    ["obj." + "" + typeImg + ""]: []
                  });
                  app.alert("警告", "请点击拍摄清晰人脸头像!");
                }
              }
            });
          } else {
            this.setData({
              ["obj." + "" + typeImg + "_fail"]: true,
            });
          }
        });
      }
    });
  },
  /**
   * 预览图片
   */
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: ['' + e.currentTarget.id + ''] // 需要预览的图片http链接列表
    })
  },
  /**
   * 删除图片
   */
  onDelCancel: function(e) {
    let type1 = e.currentTarget.dataset.type;
    let index = this.data.obj["" + type1 + ""].indexOf(e.currentTarget.id);
    if (index > -1) {
      this.data.obj["" + type1 + ""].splice(index, 1);
    }
    if (type1 == "identity_img_url") {
      this.setData({
        ["obj." + type1 + ""]: this.data.obj["" + type1 + ""],
        hidePlus: true
      });
    } else {
      this.setData({
        ["obj." + type1 + ""]: this.data.obj["" + type1 + ""],
        hidePhotoPlus: true
      });
    }
  },
  //取消拍照
  cancelPhoto: function(e) {
    let type1 = e.currentTarget.dataset.type;
    this.setData({
      camera: false
    });
  },
  getValue: function(e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      ["obj." + type]: e.detail.value
    });
    return config.getValue(e);
  },
  /**
   * 提交
   */
  onSubmit: function(e) {
    if (this.data.obj["identity_img_url"].length == 0) {
      this.setData({
        error: "请上传清晰身份证正面"
      });
    } else if (this.data.obj["head_img_url"].length == 0) {
      this.setData({
        error: "请上传本人头像"
      });
    }  else if (this.data.roomId.length == 0) {
      this.setData({
        error: "请选择居住地址"
      });
    } else if (this.data.is_native.length == 0) {
      this.setData({
        error: "请选择居住类型"
      });
    } else if (this.data.people_type.length == 0) {
      this.setData({
        error: "请选择人员类型"
      });
    } else if (this.data.obj["mobile_num"].length != 0 && this.data.obj["mobile_num"].length != 11) {
      this.setData({
        error: "请输入正确的11位手机号码"
      });
    } else {
      app.confirm('提示', '你确定要登记吗？').then(result => {
        wx.showLoading({
          title: '保存中...',
        })
        app.wxPostRequest("/mine/getExistIdCard", {
          "InfoPeople.name": this.data.peopleInfo["name"],
          "InfoPeople.sex": this.data.peopleInfo["sex"] == "男" ? 1 : 0,
          "InfoPeople.nation": this.data.peopleInfo["nation"] + "族",
          "InfoPeople.identity_num": this.data.peopleInfo["id"],
          "InfoPeople.hometown": this.data.peopleInfo["address"],
          "InfoPeople.mobile_num": this.data.obj["mobile_num"],
          "InfoPeople.head_img_url": this.data.obj["head_img_url"],
        }).then(result => {
          if (result.data.code == 1) {
            wx.showLoading({
              title: '保存中...',
            })
            let data = result.data.data;
            this.bindPeople(data);
          } else {
            app.alert("警告", result.data.msg)
          }
        });
      });

    }
  },
  chooseAddress: function(e) {
    this.setData({
      error: "请先小区选择"
    });
  },

  bindPeople: function(peopleId) {
    app.wxPostRequest("/mine/bindPeople", {
      user_id: app.globalData.userInfo["user_id"],
      people_id: peopleId
    }).then(resultW => {
      if (resultW.data.code == 1) {
        app.globalData.userInfo["people_id"] = peopleId;
        wx.setStorageSync("peopleId", peopleId);
        app.wxPostRequest("/mine/getBindYard", {
          "people_id": peopleId,
          "room_id": this.data.roomId,
          "room_name": this.data.roomName,
          "area_code": this.data.yard[2],
          "is_native": this.data.is_native,
          "relation": this.data.people_type
        }).then(result => {
          if (result.data.code == 1) {
            var data = result.data.data;
            app.getUserInfo().then(() => {
              app.alert("温馨提示", result.data.msg).then(() => {
                wx.reLaunch({
                  url: '/pages/index/welcome/welcome'
                })
              });
            })
          } else {
            app.alert("警告", result.data.msg);
          }
        });
      } else {
        app.alert("警告", result.data.msg);
      }
    });
  },
  onJump: function() {
    wx.showToast({
      title: '欢迎使用！',
      success: function() {
        setTimeout(function() {
          wx.reLaunch({
            url: '/pages/index/welcome/welcome',
          })
        }, 1200)
      }
    })
  }
})